import axios from 'axios';

const api = axios.create({
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true,
});

// 请求拦截器：添加token
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    // 确保Authorization头的格式正确，使用Bearer前缀
    config.headers.Authorization = `Bearer ${token}`;
    console.log('Adding token to request:', config.url);
  } else {
    console.log('No token available for request:', config.url);
  }
  return config;
}, (error) => {
  console.error('Request interceptor error:', error);
  return Promise.reject(error);
});

// 响应拦截器：处理认证错误
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 处理401和403错误
    if (error.response && (error.response.status === 401 || error.response.status === 403)) {
      console.error('认证失败，重定向到登录页面');
      // 清除本地存储的token
      localStorage.removeItem('token');
      // 如果不是登录页面，重定向到登录页面
      if (window.location.pathname !== '/login' && window.location.pathname !== '/register') {
        window.location.href = '/login';
      }
    }
    return Promise.reject(error);
  }
);

// 认证相关API
export const auth = {
  register: (data: { username: string; email: string; password: string }) =>
    api.post('/api/register', data),
  login: (data: { username: string; password: string }) =>
    api.post('/api/login', data),
  getCurrentUser: () => api.get('/api/me'),
  // 用户管理API
  getUsers: () => api.get('/api/users'),
  addUser: (data: { username: string; email: string; password: string; role?: string }) =>
    api.post('/api/users', data),
  updateUser: (userId: number, data: { username?: string; email?: string; password?: string; role?: string }) =>
    api.put(`/api/users/${userId}`, data),
  deleteUser: (userId: number) =>
    api.delete(`/api/users/${userId}`),
};

// 聊天相关API
export const chat = {
  getMessages: (conversationId?: string) =>
    api.get('/api/messages', { params: { conversation_id: conversationId } }),
  sendMessage: (data: { content: string; conversation_id?: string; model?: string }) =>
    api.post('/api/messages', data),
  getConversations: () => api.get('/api/conversations'),
  deleteConversation: (conversationId: string) =>
    api.delete(`/api/conversations/${conversationId}`),
};

// 数据上传和摘要相关API
export const data = {
  // 上传文件
  uploadFile: (file: File) => {
    const formData = new FormData();
    formData.append('file', file);
    return api.post('/api/data/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },
  // 获取上传列表
  getUploads: () => api.get('/api/data/uploads'),
  // 获取单个上传详情及其摘要数据
  getUploadDetails: (uploadId: number) =>
    api.get(`/api/data/uploads/${uploadId}`),
  // 搜索摘要
  searchSummaries: (params: { 
    query: string, 
    page: number, 
    per_page: number, 
    search_type: 'summary' | 'dialogue' | 'keywords' | 'all',
    chat_only?: boolean
  }, signal?: AbortSignal) =>
    api.get('/api/data/search', { params, signal }),
  // 更新摘要
  updateSummary: (summaryId: number, data: { summary: string }) =>
    api.put(`/api/summaries/${summaryId}`, data),
  // 使用模型生成摘要
  generateSummary: (data: { dialogue: string; model: string; summary_id: number }) =>
    api.post('/api/summaries/generate', data),
};

export default api; 